package com.landimc.sms.compoent;

import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.landimc.sms.entity.AliYunSms;
import com.landimc.sms.entity.Logs;
import com.landimc.sms.utils.AliYunSmsHelper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yang
 * @version 1.0
 * @date 2020/10/26 14:22
 */
@Slf4j
@Component
public class AliYunSmsReceive {

    @Autowired
    private AliYunSmsHelper aliYunSmsHelper;

    @Autowired
    private TimedCache<Long, AtomicInteger> timedCache;

    @Autowired
    private TimedCache<String, Logs> logsTimedCache;

    /**
     * 阿里云短信监听
     *
     * @param content
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queuesToDeclare = @Queue(value = "aliyun_sms_queue"), concurrency = "8")
    public void receive(String content, Message message, Channel channel) throws IOException {
        JSONObject aliYunJsonObject = JSONObject.parseObject(content);
        AliYunSms aliYunSms = JSON.toJavaObject(aliYunJsonObject, AliYunSms.class);
        log.info("messageId" + message.getMessageProperties().getMessageId());
        String result = null;
        try {
            result = aliYunSmsHelper.sendMessage(aliYunSms);
        } catch (ClientException e) {
            log.error("触发异常{}", e);
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(result)) {
            log.info("消息tag:{}号码:{}发送失败,阿里接口未返回任何参数!", message.getMessageProperties().getDeliveryTag(), aliYunSms.getPhone());
        } else {
            Map maps = (Map) JSON.parse(result);
            if (maps.get("Code").equals("OK")) {
                //请求成功对消息进行签收
                log.info("消息tag:{}号码:{}签收成功!", message.getMessageProperties().getDeliveryTag(), aliYunSms.getPhone());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                logsTimedCache.put("logs-" + aliYunSms.getIdentifier(), new Logs(message.getMessageProperties().getDeliveryTag(), aliYunSms.getPhone()[0], "SUCCESS", DateUtil.now(), result));
            } else {
                if (timedCache.get(aliYunSms.getIdentifier()) == null) {
                    timedCache.put(aliYunSms.getIdentifier(), new AtomicInteger(1));
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                } else {
                    if (timedCache.get(aliYunSms.getIdentifier()).get() >= 3) {
                        //请求失败重新排队大于三次发送失败 人工处理
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                        log.info("超过三次未成功发送请进行处理 消息tag:{} 电话号码:{}", message.getMessageProperties().getDeliveryTag(), aliYunSms.getPhone());
                        logsTimedCache.put("logs-" + aliYunSms.getIdentifier(), new Logs(message.getMessageProperties().getDeliveryTag(), aliYunSms.getPhone()[0], "FAIL", DateUtil.now(), result));
                    } else {
                        AtomicInteger atomicInteger = new AtomicInteger(timedCache.get(aliYunSms.getIdentifier()).addAndGet(1));
                        timedCache.put(aliYunSms.getIdentifier(), atomicInteger);
                        //请求失败重新排队
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                    }
                }
            }
        }
    }

}
